package com.lalilu.lmedia

import com.lalilu.lmedia.entity.LSong
import com.lalilu.lmedia.extension.Retriever
import com.lalilu.lmedia.indexer.BaseLibrary
import com.lalilu.lmedia.repository.LyricSourceEmbedded
import com.lalilu.lmedia.repository.LyricSourceFactory
import com.lalilu.lmedia.repository.LyricSourceLocal
import org.koin.dsl.module

object LMedia : BaseLibrary(), Retriever {
    enum class State {
        STATE_INITIALIZING,
        STATE_READY,
        STATE_ERROR,
        STATE_RELEASE
    }

    private var state: State = State.STATE_INITIALIZING
    private val readyCallback = mutableListOf<() -> Unit>()

    override fun getSongById(mediaId: String): LSong? =
        getSongOrNull(mediaId)

    fun whenReady(callback: () -> Unit) {
        if (state == State.STATE_READY) {
            callback()
            return
        }
        readyCallback.add(callback)
    }

    fun updateState(newState: State) {
        if (state == newState) return

        if (state == State.STATE_INITIALIZING && newState == State.STATE_READY) {
            for (callback in readyCallback) callback()
            readyCallback.clear()
        }
        state = newState
    }

    val module = module {
        single { LyricSourceEmbedded() }
        single { LyricSourceLocal() }
        single { LyricSourceFactory(get<LyricSourceEmbedded>(), get<LyricSourceLocal>()) }
    }
}